<template>
  <el-card shadow="never">
    <div slot="header">
      <span>{{pageTitle}}</span>
    </div>
    <el-divider content-position="left">核查计划信息</el-divider>
    <el-row>
      <el-form
        disabled
        class="table_form_wrap"
        ref="planForm"
        :model="planForm"
        label-width="100px"
      >
        <el-col :span="12">
          <el-form-item label="计划名称" prop="planName">
            <el-input
              v-model.trim="planForm.planName"
              placeholder="请输入计划名称"
              show-word-limit
              maxlength="50"
            />
          </el-form-item>
          <el-form-item label="核查时间" prop="planYear">
            <el-date-picker
              v-model="planForm.planYear"
              value-format="yyyy"
              type="year"
              placeholder="选择年">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划拟定人" prop="createUser">
            <el-input
              readonly
              v-model.trim="planForm.createUser"
            />
          </el-form-item>
          <el-form-item label="拟定时间" prop="createTime">
            <el-date-picker
              v-model="planForm.createTime"
              type="datetime">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <el-divider content-position="left">核查供应商明细</el-divider>
    <basic-table
      showTableIndex
      :headerBeyondHide="false"
      :showActionCol="false"
      :loading="tableInfo.loading"
      :columns="tableInfo.columns"
      :dataSource="tableInfo.list"
      :maxTableHeight="500"
    >
      <el-row slot="content_context" type="flex" justify="space-between" align="middle">
        <el-radio-group v-model="timeRange.value" @change="handleSelectTimeRange">
          <el-radio
            v-for="time in timeRange.list"
            :key="time.value"
            :label="time.value"
          >{{ time.label }}</el-radio>
        </el-radio-group>
        <el-button
          size="mini"
          @click="handleConfigTableColumns"
          >字段显示设置</el-button>
      </el-row>
    </basic-table>
    <el-divider />
    <el-row type="flex" justify="center" class="footer">
      <el-button v-if="isEdit" type="primary" :loading="submitLoading" @click="handleSubmit">提交</el-button>
      <el-button @click="handleBack">返回</el-button>
    </el-row>
    <ConfigTableColumnsDialog
      :menuId="MENU_ID"
      v-if="fieldSettingVisible"
      :dialogVisible="fieldSettingVisible"
      @handleClose="handleConfigTableColumnsDialogClose"
      @handleSubmit="hanldSubmitTableColumnsConfig" />
  </el-card>
</template>
<script>
import { setAuthBtnId } from '@/utils/bizUtils';
import BasicTable from '@/components/skusTable';
import ConfigTableColumnsDialog from '@/pages/supplier/components/configTableColumnsDialog';
import { getListColumnSettings } from '@/api/supplier/components';
import {
  submitEditCheckTypeService,
  queryCheckPlanListService,
  queryCheckSupplierDetailService
} from '@/api/supplier/supervision/checkPlan';
import {
  CHECK_TIME_TYPE_OPTIONS,
  MONTH_OPTIONS,
  QUARTER_OPTIONS,
  HALF_YEAR_OPTIONS,
  YEAR_OPTIONS,
  DEPARTMENT_OPTIONS,
  WHETHER_OPTIONS,
  CHECK_TYPE_OPTIONS,
  EXCEPTION_TYPE_OPTIONS
} from '../constants'
import { MENU_ID } from './constants'

export default {
  components: {
    BasicTable,
    ConfigTableColumnsDialog
  },
  data () {
    return {
      MENU_ID,
      timeRange: {
        value: '',
        list: [
          { label: '全部', value: '' },
          { label: '近30天内', value: 30 },
          { label: '近60天内', value: 60 },
          { label: '近90天内', value: 90 },
          { label: '近180天内', value: 180 },
        ]
      },
      timeObj: {
        1: MONTH_OPTIONS,
        2: QUARTER_OPTIONS,
        3: HALF_YEAR_OPTIONS,
        4: YEAR_OPTIONS,
      },
      fieldSettingVisible: false,
      planId: '',
      planForm: {
        planName: '',
        planYear: '',
        createUser: '',
        createTime: '',
      },
      tableInfo: {
        list: [],
        selection: [],
        columns: [],
        loading: false
      },
      submitLoading: false,
    }
  },
  computed: {
    isEdit () {
      return this.pageType == 'edit'
    },
    pageTitle () {
      return this.isEdit ? '修改核查方式' : '查看核查计划';
    }
  },
  created () {
    this.getColSettings()
    const { planId, type, processBillId } = this.$route.query;
    this.pageType = type;
    this.planId = planId;
    this.processBillId = processBillId;
    // 获取核查供应商明细
    this.getSupplierDetail()
    // 获取核查计划信息
    this.getPlanInfoData()
  },
  methods: {
    // 选择时间筛选范围
    handleSelectTimeRange (val) {
      console.log(val)
      this.getSupplierDetail(val)
    },
    // 获取核查计划信息
    async getPlanInfoData () {
      setAuthBtnId();
      const res = await queryCheckPlanListService(
        { id: this.planId },
      );
      if (res?.result) {
        const {
          planName,
          planYear,
          createUser,
          createTime
        } = res.result.records[0];
        this.planForm = {
          planName,
          planYear: planYear ? planYear.toString() : '',
          createUser,
          createTime
        }
      }
    },
    // 获取核查供应商信息
    async getSupplierDetail (intervalDays = '') {
      const res = await queryCheckSupplierDetailService(
        { planId: this.planId, processBillId: this.processBillId, intervalDays },
        state => { this.tableInfo.loading = state }
      );
      if (res?.result) {
        this.tableInfo.list = res.result.records
      }
    },
    // 获取列表配置
    async getColSettings () {
      const { status, result = [] } = await getListColumnSettings({ menuId: MENU_ID })
      if (status === '0') {
        this.setTableColumns(result)
      }
    },
    // 应用列表配置
    setTableColumns (data) {
      const columnList = data.filter(i => i.isShow).map(i => {
        return {
          title: i.label,
          key: i.prop,
          width: i.width
        }
      })
      // 是否核查 isCheck 是否季节性商品 isSeasonalGoods 是否库存商品 isStockGoods
      const whetherFileList = ['isCheck', 'isSeasonalGoods', 'isStockGoods']
      const areaFileList = ['provinceName', 'cityName', 'areaName', 'noCheckReason']
      this.tableInfo.columns = columnList.map((i) => {
        // 异常类型
        if (i.key === 'exceptionType') {
          i.render = (h, { row }) => {
            return <el-select disabled size='mini' v-model={row.exceptionType}>
              { EXCEPTION_TYPE_OPTIONS.map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
            </el-select>
          }
        }
        // 核查部门
        if (i.key === 'deptId') {
          i.render = (h, { row }) => {
            return <el-select disabled size='mini' v-model={row.deptId}>
              { DEPARTMENT_OPTIONS.map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
            </el-select>
          }
        }
        // 核查方式 checkTypeOldName
        if (i.key === 'checkType') {
          i.render = (h, { row }) => {
            if (row.checkTypeOldName) {
              return <el-tooltip class="item" effect="dark" content={`原值：${row.checkTypeOldName}`} placement="left">
                <el-select disabled={!this.isEdit} size='mini' v-model={row.checkType}>
                  { CHECK_TYPE_OPTIONS.map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
                </el-select>
              </el-tooltip>
            }
            return <el-select disabled={!this.isEdit} size='mini' v-model={row.checkType}>
              { CHECK_TYPE_OPTIONS.map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
            </el-select>
          }
        }
        // 核查维度
        if (i.key === 'checkDimension') {
          i.render = (h, { row }) => {
            return <el-select disabled size='mini' v-model={row.checkDimension}>
              { CHECK_TIME_TYPE_OPTIONS.map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
            </el-select>
          }
        }
        // 核查时间
        if (i.key === 'checkTimePeriod') {
          i.render = (h, { row }) => {
            return <el-select disabled size='mini' v-model={row.checkTimePeriod}>
              { row.checkDimension && this.timeObj[row.checkDimension].map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
            </el-select>
          }
        }
        // 核查人id
        if (i.key === 'checkUserCode') {
          i.render = (h, { row }) => {
            return <el-input
              disabled
              size='mini'
              v-model={row.checkUser}
              placeholder="请选择核查人"
              suffix-icon="el-icon-search"
              onFocus={() => { this.showHrDialog(row) }}
            />
          }
        }
        // 是否选项
        if (whetherFileList.includes(i.key)) {
          i.render = (h, { row }) => {
            return <el-select disabled size='mini' v-model={row[i.key]}>
              { WHETHER_OPTIONS.map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
            </el-select>
          }
        }
        // 省市区 不核查原因
        if (areaFileList.includes(i.key)) {
          i.render = (h, { row }) => {
            return <el-input disabled size='mini' v-model={row[i.key]} />
          }
        }
        return i
      })
    },
    // 列表字段配置
    handleConfigTableColumns () {
      this.fieldSettingVisible = true;
    },
    // 字段显示设置弹窗关闭
    handleConfigTableColumnsDialogClose () {
      this.fieldSettingVisible = false;
    },
    // 提交字段显示设置
    hanldSubmitTableColumnsConfig (data) {
      this.setTableColumns(data)
      this.fieldSettingVisible = false;
    },
    handleSubmit () {
      if (this.tableInfo.list.length === 0) {
        return this.$message.warning('核查供应商明细不能为空')
      }
      const submitData = {
        planId: this.planId,
        list: this.tableInfo.list.map(item => ({
          checkType: item.checkType,
          id: item.id,
        }))
      }
      this.submitAciton(submitData)
    },
    async submitAciton (data) {
      const res = await submitEditCheckTypeService(data, state => { this.submitLoading = state })
      if (res) {
        this.$message.success('提交成功')
        this.handleBack()
      }
    },
    handleBack () {
      this.$router.push({ name: 'checkPlanList' })
    }
  }
}
</script>
<style scoped>
.upload {
  display: inline;
  margin: 0 10px;
}
.right-btn {
  float: right;
}
</style>
